#include "common.h"

#include "ui.h"
#include "numbers.h"

Numbers::Numbers( DWORD posX, DWORD posY )
:	UI()
,	_color( 0xFF000000 )
,	_kerningRatio( 1.0f )
,	_point( 64 )
,	_pTexture( NULL )
{
	SetStartPos( posX, posY );
	SetRect( 0, 0, 40, 64 );
}

Numbers::~Numbers()
{
	if( _pTexture )
	{
		_pTexture->Release();
		_pTexture = NULL;
	}
}

void Numbers::ActualDraw()
{
	D3DXMATRIX matOld, matNew;

	UI::GetSprite()->GetTransform( &matOld );

	D3DXMatrixIdentity( &matNew );
	matNew._11 = matNew._22 = matNew._33 = _point / 64.0f;
	matNew._41 = GetStartPos().x; 
	matNew._42 = GetStartPos().y;

	int offset = GetRect().right - GetRect().left;
	int offsetX = 0;
	const char* buf = _numbers.c_str();
	for( size_t i = 0; i < _numbers.length(); ++i )
	{
		UI::GetSprite()->SetTransform( &matNew );

		int n = buf[i];
		if( '0' <= n && n <= '9' )
		{
			// ASCII '0' == 48
			n -= 48;
		}
		else if( n == ':' )
		{
			n = 10;
		}
		else
		{
			continue;
		}

		if( i > 0 )
		{
			int nMinus1 = buf[i-1];
			if( '0' <= nMinus1 && nMinus1 <= '9' )
			{
				offsetX += ( offset + static_cast< int >( offset * ( _kerningRatio - 1.0f ) ) );
			}
			else if( nMinus1 == ':' )
			{
				offsetX += ( static_cast< int >( offset * 0.4 ) );
			}
		}

		SetRect( n*offset, 0, (n+1)*offset, 64 );
		//offsetX += ( offset + static_cast< int >( offset * ( _kerningRatio - 1.0f ) ) );
		UI::GetSprite()->Draw( _pTexture, &GetRect(), NULL, &D3DXVECTOR3( (float)offsetX, 0, 0 ), _color );
	}
	UI::GetSprite()->SetTransform( &matOld );
}

void Numbers::SetImage( LPCWSTR filePath )
{
	LPDIRECT3DDEVICE9 device = Core::GetInstance().GetD3dDevice();

	if( FAILED( D3DXCreateTextureFromFile( device, filePath, &_pTexture ) ) )
	{
		// error
		assert( false );
	}
}